<?php

// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\portal\controller;

use cmf\controller\HomeBaseController as CmfHomeBaseController;
use tree\Tree;
use think\facade\Db;
use think\View;

class HomeBaseController extends CmfHomeBaseController {

    public $cache_time = '1';  // 首页接口数据缓存时间
    
    /**
     *
     * @var type 
     * @禁止修改 红色一级警告
     */
    protected $view_share_var = array(
        //变量调用    product_category_list
    // 'type'=>1  二级栏目和导航下对应列表（item.list）  
    // 'type'=>2  列表 
    // 'type'=>3  二级栏目
        PRODCUT_CATEGORY_LIST => array( // 产品分类列表 ，对应控制器ProductController,  
            'position' => true,'type'=>1,'isSelect'=>true,'controller'=>'product'
        ), 
        NEWS_CATEGORY_LIST => array(//新闻分类列表,对应控制器NewsController
            'position' => false,'type'=>1,'isSelect'=>true,'controller'=>'news'
        ), 
        //案例分类列表，对应控制器CaseController
        CASE_CATEGORY_LIST => array(
            'position' => false,'type'=>2,'isSelect'=>true,'controller'=>'case'
        ),  
        PRODCUT_RECOMMEND_LIST => array( // 产品推荐列表 ，对应控制器ProductController,  
            'position' => false,'type'=>2,'isSelect'=>true,'controller'=>'product'
        ),
        NEWS_RECOMMEND_LIST => array( // 新闻推荐列表 ，对应控制器ProductController,  
            'position' => false,'type'=>2,'isSelect'=>true,'controller'=>'news'
        ),
        CASE_RECOMMEND_LIST => array( // 案例推荐列表 ，对应控制器ProductController,  
            'position' => false,'type'=>2,'isSelect'=>true,'controller'=>'case'
        ),      
    );        



    public function initialize() {

        parent::initialize();    
        $assign_data = array();
        $cache_data = cache('PORTAL_BASE_INFO');
        

        if(empty($cache_data)){
            foreach ($this->view_share_var as $key=>$value){            
                $class = __NAMESPACE__ .'\\'.ucfirst($value['controller']) .'Controller';
                $workClass_by_classname = new \ReflectionClass($class);          
            
                if(!empty($workClass_by_classname->hasProperty ('view_share_arr'))){
                    $data = $workClass_by_classname->getDefaultProperties()['view_share_arr'];         
                    $request_data = $data[$key];
                    $request_data['key_name'] = $key;
                    $response_data = $this->setViewShareInfo($request_data);                    
                    $assign_data[$key] = $response_data;
                }                

            }  
            cache('PORTAL_BASE_INFO', json_encode($assign_data) , $this->cache_time);
        }else{
            $assign_data = json_decode($cache_data,TRUE);
        }
        $this->assign($assign_data);               
    }

    

    


    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array  $vars     模板输出变量
     * @param array  $replace  模板替换
     * @param array  $config   模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [],$assign_data = [])
    {
 
        $assign_data = array();
        
        $current_url = $this->dealUrl();
       
        $data = $this->navMenusTreeArray();
        
        $banner = $this->getBanner();
        $link = $this->getLink();
        

 
        
        $assign_data = array(
            'data' => $data,
            'current_url' => '/'.$current_url,
            'banner' => $banner, 
            'link' => $link,    
        );
       $this->assign($assign_data);
//        $content = parent::fetch($template , $vars, $replace , $config , $assign_data );
        $content = parent::fetch($template , $vars , $config );
        
        $content = cmf_filter_content($content);
       
        return $content;

              
    }


    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array  $vars     模板输出变量
     * @param array  $replace  模板替换
     * @param array  $config   模板参数
     * @return mixed
     */
    protected function setViewShareInfo($view_key){
        
        if(!is_array($view_key))$view_key_arr = array($view_key);
        else $view_key_arr = $view_key;      
        $key = $view_key_arr['key_name'];
      
        if(!empty($this->view_share_var[$key])){
            if(!empty($this->view_share_var[$key]['isSelect'])){   
                $select_type = empty($this->view_share_var[$key]['type']) ? 2 :$this->view_share_var[$key]['type'];

                $data = $this->getData($view_key_arr,$select_type);


                return $data;

            }
        }
            
    }


    



    public function navMenusTreeArray($navId = 0, $maxLevel = 0)
    {
        
        if(empty(cache('NAV_MENU_LIST'))){            
            if (empty($navId)) {
                $navId = Db::name('nav')->where('is_main', 1)->value('id');
            }
            $navMenus     = Db::name('nav_menu')->where('nav_id', $navId)->where('status', 1)->order('list_order ASC')->select()->toArray();
            $navMenusTree = [];
            if (!empty($navMenus)) {
                $tree = new Tree();
                $this->parseNavMenu4Home($navMenus);
                $tree->init($navMenus);

                $navMenusTree = $tree->getTreeArray(0, $maxLevel);
            }
            $sub_list = array('product','case','news');

            foreach ($navMenusTree as &$value){
                foreach($sub_list as $val){
                    if(strpos($value['href'],$val) !== FALSE){

                        $children = $this->getSubNav($val);               
                        $value['children'] = $children;
                        break;
                    }
                }
                                    
            }
            cache('NAV_MENU_LIST',$navMenusTree, $this->cache_time);

        }
        $navMenusTree = cache('NAV_MENU_LIST');
        return $navMenusTree;
    }
    
    
    
    private function getSubNav($type){
        switch ($type){
            case 'product':
                $table = 'product_category';
                break;
            case 'case':
                $table = 'case_category';
                break;
            case 'news':
                $table = 'portal_category';
                break;
        }
        $field_str = 'id,parent_id,name';
        $where = array(
            'status' => 1,
            'delete_time' =>0
        );
        $list = Db::name($table)->where($where)->order('list_order asc')->select();
   
        
        $navMenusTree = $this->dealSubNav($list,$type);        
        return $navMenusTree;
    }
    
    
    private function dealSubNav($data,$type,$pId = 0){
        $tree = array();
        foreach ($data as $k => &$v) {
            $v['href'] = '/' .$type .'/'.$v['id'];
            if ($v['parent_id'] == $pId) {        //父亲找到儿子
                $v['children'] = $this->dealSubNav($data, $type,$v['id']);
                $tree[] = $v;
            }
        }
        return empty($tree)?'':$tree;
    }




    private function parseNavMenu4Home(&$navMenus)
    {
        foreach ($navMenus as $key => $navMenu) {
            $href    = htmlspecialchars_decode($navMenu['href']);
            $hrefOld = $href;
            if (strpos($hrefOld, "{") !== false) {
                $href = json_decode($navMenu['href'], true);
                $href = cmf_url($href['action'], $href['param']);
            } else {
                if ($hrefOld == "home") {
                    $href = request()->root() . "/";
                } else {
                    $href = $hrefOld;
                }
            }
            $navMenu['href'] = $href;
            $navMenus[$key]  = $navMenu;
        }
    }    

    
    protected function getSeoInfo(){
       
        $pathinfo = $_SERVER['PATH_INFO'];
        $pathinfo_arr = array_filter(explode('/', $pathinfo));        
        $main_info = strtolower(empty($pathinfo_arr[0]) ? '' : $pathinfo_arr[0]);


        if(empty($pathinfo_arr[1])){
            $seo_nav_info = db('nav_menu')->field('seo_title site_seo_title,seo_keywords site_seo_keywords,seo_description site_seo_description')->where('href','/'.$main_info)->find();
        }
        
        
        if(!empty($seo_nav_info))            return  $seo_nav_info;
         
        if(empty($seo_nav_info) && !empty($pathinfo_arr[1])){
            
            $table_info = array('product','case','portal');            
          
            if(strpos($main_info, 'detail')){ //详情
                $table_pre = str_replace('detail', '',$main_info);
                $table = $table_pre . '_category';
            }else{ //列表
                $table_pre = $main_info;   
                $table = $table_pre . '_category';
            }
    
            
            if(!in_array($table_pre, $table_info)) return array();
            $where = array(
                'id' => $pathinfo_arr[1],
            );
            $seo_nav_info = db($table)->field('seo_title site_seo_title,seo_keywords site_seo_keywords,seo_description site_seo_description')->where($where)->find();
            $seo_nav_info = empty($seo_nav_info) ? array() :$seo_nav_info;
            return $seo_nav_info;
           
        }
                
        return array();
        
        
        
    }





    public function dealUrl(){
        $current = request()->url();
        
        $current = trim($current,'/');
        if(strpos($current, '/')){
            $href = substr($current, 0, strpos($current, '/'));
        }else $href = $current;

//        return $url;
        return str_replace('detail', '', strtolower($href));
    }
   
    
      
/**
     * 
     * @param array $data    数据表信息
     * @param type $type 值为1时，取出全部分类下的前几条数据，值为2时，取出前几条数据
     * @return type
     */
    public function getData($data,$type = 2){
        
        $request_data = array(
            'data_table' => empty($data['data_table']) ? $data['table_pre'].'_post' : $data['data_table'],         
        );
        
        switch($type){
            case 1: //获取每个分类下的前几条数据，即tab选项卡
                $request_data['category_table'] = $data['table_pre'].'_category';
                $request_data['relation_table'] = $data['table_pre'].'_category_post';
                
                $request_data = array_merge($request_data,$data);
                $return_data = $this->_getClassTopData($request_data);
                                
                break;
            case 2:  //获取产品/案例/新闻的前几条数据
                $return_data = Db::name($request_data['data_table'])
                        ->alias('post')
                        ->field($data['field'])
                        ->where($data['where'])
                        ->limit($data['limit'])
                        ->order($data['order'])
                        ->select()
                        ->toArray();

                foreach ($return_data as &$value){         
                    if(!empty($value['more']))$value['more'] = json_decode($value['more'],TRUE);           
                }
                break;
            case 3://获取产品/案例/新闻的分类
                $request_data['category_table'] = $data['table_pre'].'_category';
                $request_data = array_merge($request_data,$data);
                $return_data = $this->getCategoryData($request_data);
                                
                break;
        }
    
       
        
           
        return $return_data;
        
    }
    
    
    public function getCategoryData($request_data){
        $data = array();       
        $category = Db::name($request_data['category_table'])
                ->alias('category')
                ->where('status','1')
                ->where('delete_time','0')
                ->order('category.list_order asc')
                ->column('category.id,category.name,category.ename,category.parent_id,category.more');
        foreach ($category as $key=>$value){
                
            $value['list'] = array();

           // $value['more'] = json_decode($value['more'],true);

            //dump($value);die();

            $k = empty($value['ename']) ? $key : $value['ename'];


            
            $data[$k] = $value;
        }
        if (!empty($data)) {
            $tree = new Tree();
            $tree->init($data);

            $data = $tree->getTreeArray(0, $data);
        }
        return $data;
    }
    
    
    
    
    public function _getClassTopData($request_data){ 
        $_data = $data = array();       
        $category = Db::name($request_data['category_table'])
                ->alias('category')
                ->where('status','1')
                ->where('delete_time','0')  
                ->order('category.list_order asc')
                
                ->column('category.id,category.name,category.ename,category.description,more');
   
        
        if(!empty($category)){
            $category_id = array_keys($category);
            $list = array();
            foreach($category_id as $key=>$value){
                $table_sql = Db::name($request_data['data_table'])
                    ->alias('post')
                    ->field('relation.`category_id` ,post.recommended,'.$request_data['field'])
                    ->join('cmf_'.$request_data['relation_table'].' relation','relation.post_id = post.id')
                    ->where('relation.category_id',$value)  
                    
                    ->where($request_data['where'])
                    ->limit($request_data['limit'])
                    ->order($request_data['order'])
                    ->buildSql();
                $_list =Db::query($table_sql);
                $list = array_merge($list,$_list);
            }
            
//            $table_sql = Db::name($request_data['data_table'])
//                    ->alias('post')
//                    ->field('relation.`category_id` ,post.recommended,'.$request_data['field'])
//                    ->join('cmf_'.$request_data['relation_table'].' relation','relation.post_id = post.id')
//                    ->where('relation.category_id','in',$category_id)  
//                    ->where($request_data['where'])
//                    ->order($request_data['order'])
//                    ->buildSql();
//            $sql = 'SELECT * FROM ' . $table_sql .'a WHERE (SELECT COUNT(*) FROM '.$table_sql.' b WHERE b.category_id = a.category_id AND b.id > a.id) < '.$request_data['limit'].' ORDER BY a.recommended desc,a.category_id,a.id desc';
            
        
             
            foreach ($list as $item){
                $item['more'] = json_decode($item['more'],TRUE);
                $_data[$item['category_id']][] = $item;
            }
            
            foreach ($category as $key=>$value){
                $middle_data = empty($_data[$key]) ? array() : $_data[$key];
                
                $value['list'] = $middle_data;  
                $value['more'] = json_decode($value['more'],true);           
                $k = empty($value['ename']) ? $key : $value['ename'];
                
                $data[$k] = $value;
            }
        }
        return $data;
    }
    
    /**
     * 
     * @return type
     * @获取轮播图
     */
    public function getBanner(){
        $slide_id  = empty(cmf_is_mobile()) ? 1 : 3;
        $banner = Db::name('slide_item')->where(['slide_id'=>$slide_id,'status'=>1])->order('list_order asc')->select();

        return $banner;
    }
    
    
     /**
     * 
     * @return type
     * @获取友情链接
     */
    public function getLink(){
        $link = Db::name('link')->where('status',1)->order('list_order asc')->select();



        return $link;
    }
    
    
}
